<?php

namespace app\agent\model\order;

use app\common\facade\auth\Auth;
use app\model\TakeoutOrder;
use think\facade\Db;
use app\common\model\Export;

/**
 * 外卖订单
 */
class Takeout
{
    private $table = 'takeout_order';

    /**
     * 列表.
     */
    public function getList($params)
    {
        $where = [];

        $agentIds = [];
        if (Auth::from() == FROM_APP_YMSH){  //有美生活对接的自动识别Agent
            $agentIds = Auth::allBindAgentIds();
        }else{
            $where[] = ['agent_id', '=', $params['agent']['id']];
            $agentIds[] = $params['agent']['id'];

        }

        if (!empty($params['channel_id'])) {
            $where[] = ['channel_id', '=', $params['channel_id']];
        }
        $orderId = trim($params['order_id'] ?? '');
        if ($orderId) {
            $where[] = ['order_id', '=', $orderId];
        }
        if (!empty($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }
        if (!empty($params['order_type'])) {
            $where[] = ['order_type', '=', $params['order_type']];
        }
        if (!empty($params['ordertime'])) {
            $where[] = ['ordertime', '>=', strtotime($params['ordertime'][0])];
            $where[] = ['ordertime', '<=', strtotime($params['ordertime'][1] . ' 23:59:59')];
        }

        $paginate = [
            'page' => $params['page'] ?? 1,
            'list_rows' => $params['list_rows'] ?? 10,
        ];
        $channelList = Db::name('agent_channel')
            ->field('id, name')
            ->whereIn('agent_id', $agentIds)
            ->where('is_deleted', 0)
            ->order('name asc')
            ->select()
            ->toArray();
        $channel = array_column($channelList, 'name', 'id');

        $list = TakeoutOrder::query()
            ->withSearch(['app_id','merchant_id'],request()->all())
            ->where($where)
            ->order('id desc');

        // 导出数据字段处理
        if (!empty($params['is_export'])) {
            $list = $list->select()->toArray();
            $res = [];
            $title = ['订单号', '所属平台', '渠道', '产品名称', '订单金额', '预估佣金', '状态', '下单时间'];
            $orderTypeMap = [
                1 => '美团',
                2 => '饿了么',
                3 => '美团到店',
            ];
            $statusMap = [
                8 => '已完成',
                9 => '已取消',
            ];
            foreach ($list as $v) {
                if ($v['ordertime']) {
                    $v['ordertime'] = date('Y-m-d H:i:s', $v['ordertime']);
                } else {
                    $v['ordertime'] = '';
                }
                $res[] = [
                    $v['order_id']."\t",
                    $orderTypeMap[$v['order_type']],
                    $channel[$v['channel_id']] ?? '',
                    $v['title'],
                    fen2yuan($v['payprice']).'',
                    fen2yuan($v['profit']).'',
                    $statusMap[$v['status']] ?? '已支付',
                    $v['ordertime'],
                ];
            }
            unset($list);
            $export = new Export;
            $name = '外卖订单';
            return $export->downloadExcel($title, $res, $name);
        }

        $list = $list->paginate($paginate)->toArray();
        if ($list['data']) {
            $updatedAt = date('Y-m-d H:i:s', time() - 600);
            foreach ($list['data'] as $k => $v) {
                $list['data'][$k]['channel_name'] = $channel[$v['channel_id']] ?? '';
                if ($v['ordertime']) {
                    $list['data'][$k]['ordertime'] = date('Y-m-d H:i:s', $v['ordertime']);
                } else {
                    $list['data'][$k]['ordertime'] = '';
                }
                $list['data'][$k]['order_id'] = strval($v['order_id']);

                // status = 1 且 更新时间超过 10 分钟的，前端可以点更新
                if ($v['status'] == 1 && $v['updated_at'] < $updatedAt) {
                    $list['data'][$k]['can_update'] = 1;
                } else {
                    $list['data'][$k]['can_update'] = 0;
                }
            }
        }
        $list['channelList'] = $channelList;

        return success('操作成功', $list);
    }

    /**
     * 更新美团、饿了么订单状态
     */
    public function updateOrder($params)
    {
        if (empty($params['order_id'])) {
            return fail('订单号不能为空');
        }
        $orderId = $params['order_id'];

        $order = Db::name('takeout_order')
            ->where('order_id', $orderId)
            ->find();
        if (empty($order)) {
            return fail('订单不存在');
        }

        switch ($order['order_type']) {
            case TAKEOUT_ORDER_MEITUAN: // 美团
                return $this->updateMeituanOrder($order);
            case TAKEOUT_ORDER_ELE: // 饿了么
                return $this->updateEleOrder($order);
            case TAKEOUT_ORDER_MEITUAN_PUB: // 美团到店
                return $this->updateMeituanPubOrder($order);
                break;
        }
    }

    /**
     * 更新美团订单状态
     */
    private function updateMeituanOrder($order)
    {
        $orderId = $order['order_id'];
        $extra = json_decode($order['extra'], true);
        if (!isset($extra['actId'])) {
            return fail('参数有误');
        }

        try {
            $model = new \app\common\service\Meituan($order['agent_id']);
        } catch (\Exception $e) {
            return fail($e->getMessage());
        }

        $res = $model->getOrder([
            'actId' => $extra['actId'],
            'orderId' => $orderId,
        ]);
        if (empty($res['data']) || !isset($res['data']['status'])) {
            return fail($res['message'] ?? '订单不存在');
        }

        if ($res['data']['status'] == $order['status']) {
            Db::name('takeout_order')
                ->where('id', $order['id'])
                ->update([
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

            return fail('当前已是最新状态');
        }

        if ($res['data']['status'] != $order['status']) {
            Db::name('takeout_order')
                ->where('id', $order['id'])
                ->update([
                    'status' => $res['data']['status'],
                ]);
        }

        return success('更新成功');
    }

    /**
     * 更新饿了么订单状态
     */
    private function updateEleOrder($order)
    {
        try {
            $model = new \app\common\service\Ele($order['agent_id']);
        } catch (\Exception $e) {
            return fail($e->getMessage());
        }

        $res = $model->scOrderList([
            'startTime' => $order['ordertime'] - 180,
            'endTime' => $order['ordertime'] + 180,
            'query_type' => '2',
            'page' => 1,
            'limit' => 100,
        ]);
        if (empty($res['data']['results']['publisher_order_dto'])) {
            return fail('订单获取失败'.json_encode($res, JSON_UNESCAPED_UNICODE));
        }

        $orderList = $res['data']['results']['publisher_order_dto'];
        if (!isset($orderList[0])) {
            $orderList = [$orderList];
        }
        foreach ($orderList as $v2) {
            $check_order = Db::name($this->table)
                ->where('order_id', $v2['trade_parent_id'])
                ->where('order_type', TAKEOUT_ORDER_ELE)
                ->find();
            // 淘客订单状态，12-付款，13-关闭，14-确认收货，3-结算成功;不传，表示所有状态
            // 	订单状态( 1 已付款 8 已完成 9 已退款或风控)
            if ($v2['tk_status'] == 12 || $v2['tk_status'] == 14) {
                $status = 1;
            } elseif ($v2['tk_status'] == 3) {
                $status = 8;
            } else {
                $status = 9;
            }

            if (empty($check_order)) {
                $click_time = strtotime($v2['click_time']);
                $info = Db::name('alimama_pid_history')
                    ->where('agent_id', $order['agent_id'])
                    ->where('sub_pid', $v2['site_id'] . '_' . $v2['adzone_id'])
                    ->where('start_time', '<=', $click_time)
                    ->where('end_time', '>', $click_time)
                    ->find();
                Db::name($this->table)
                    ->insert([
                        'agent_id' => $order['agent_id'],
                        'order_type' => TAKEOUT_ORDER_ELE,
                        'order_id' => $v2['trade_parent_id'],
                        'paytime' => isset($v2['tk_paid_time']) ? strtotime($v2['tk_paid_time']) : 0,
                        'ordertime' => strtotime($v2['tk_create_time']),
                        'payprice' => yuan2fen($v2['alipay_total_price'] ?? 0),
                        'profit' => yuan2fen($v2['pub_share_pre_fee']),
                        'user_id' => $info['user_id'] ?? 0,
                        'title' => mb_substr($v2['item_title'], 0, 100),
                        'img' => $v2['item_img'],
                        'status' => $status,
                        'extra' => json_encode($v2, JSON_UNESCAPED_UNICODE),
                    ]);
            } else {
                if ($check_order['status'] == 1) {
                    Db::name($this->table)
                        ->where('id', $check_order['id'])
                        ->update([
                            'status' => $status,
                            'extra' => json_encode($v2, JSON_UNESCAPED_UNICODE),
                        ]);
                }
            }
        }

        return success('更新成功');
    }

    /**
     * 更新美团到店订单
     */
    private function updateMeituanPubOrder($order)
    {
        $orderId = $order['order_id'];

        try {
            $model = new \app\common\service\MeituanPub($order['agent_id']);
        } catch (\Exception $e) {
            return fail($e->getMessage());
        }

        $res = $model->cpsOrderList([
            'order_id' => $orderId,
        ]);
        if (empty($res['msg']['records'][0])) {
            return fail('订单不存在');
        }
        $result = $res['msg']['records'][0];
        unset($res);

        $status = null;
        // 订单状态(1已付款  8已完成  9已退款或风控 10待结算 11已结算)
        switch ($result['itemBizStatus']) {
            case 1: // 支付成功,表示订单已经完成支付
                $status = 1;
                break;
            case 2: // 核销成功，表示订单已经到店核验
                $status = 1;
                break;
            case 3: // 结算成功，标识订单已经完成结算，会有佣金
                $status = 8;
                break;
            case 99: // 无效订单：标识订单无需结算，会有结算失败理
                $status = 9;
                break;
            case 999:// 未知状态：异常订单，正常情况下不会出现该状态
                $status = 9;
                break;
        }
        if (empty($status)) {
            return fail('订单状态有误');
        }

        Db::name($this->table)
            ->where('id', $order['id'])
            ->update([
                'status' => $status,
                'payprice' => yuan2fen($result['actualItemAmount']),
                'profit' => yuan2fen($result['balanceAmount']),
                'title' => $result['shopName'],
                'img' => $result['shopImage'] ?? '//jj.dmjvip.com/static/images/mt.png',
                'extra' => json_encode($result, JSON_UNESCAPED_UNICODE),
            ]);

        return success('更新成功');
    }
}
